package com.javaweb.cwj.listen;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.javaweb.cwj.entity.EduSubject;
import com.javaweb.cwj.entity.excel.SubjectData;
import com.javaweb.cwj.exception.cwjException;
import com.javaweb.cwj.service.EduSubjectService;


public class SubjectListen extends AnalysisEventListener<SubjectData> {
    //因为eduSubejctService不能自动注入的原因是 我们在imp文件中需要new 一个subjectlisten对象 所以需要我们人工导入
    //采用构造方法注入即可
    private EduSubjectService eduSubjectService;
    public SubjectListen(EduSubjectService eduSubjectService){
        this.eduSubjectService = eduSubjectService;
    }
    public SubjectListen(){}
    //这个函数的作用是读取文件 并且是一行一行的读 所以subjectData是代表每一行的数据
    @Override
    public void invoke(SubjectData subjectData, AnalysisContext analysisContext) {
         if(subjectData==null){
              throw new cwjException(20001,"数据为空");
         }
         //判断一级目录
        EduSubject eduSubject =  this.oneSubject(subjectData,eduSubjectService);
        if(eduSubject==null){
            eduSubject = new EduSubject();
            eduSubject.setParentId("0");
            eduSubject.setTitle(subjectData.getOneSubjectName());
            //这里不用填充时间 myplus自动填充
            eduSubjectService.save(eduSubject);
        }

        //判断二级目录
        String pid = eduSubject.getId();
        EduSubject eduSubject1 = this.twoSubject(subjectData,eduSubjectService,pid);
        if(eduSubject1==null){
             eduSubject1 = new EduSubject();
             eduSubject1.setTitle(subjectData.getTwoSubjectName());
            eduSubject1.setParentId(pid);
            eduSubjectService.save(eduSubject1);
        }

    }
    //判断一级目录是否存在
    public EduSubject oneSubject(SubjectData data,EduSubjectService eduSubjectService){
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("Parent_id","0");
        queryWrapper.eq("title",data.getOneSubjectName());
        EduSubject eduSubject = eduSubjectService.getOne(queryWrapper);
        return eduSubject;
    }
    //判断二级目录是否存在
    public EduSubject twoSubject(SubjectData data,EduSubjectService eduSubjectService,String pid){
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("Parent_id",pid);
        queryWrapper.eq("title",data.getTwoSubjectName());
        EduSubject eduSubject = eduSubjectService.getOne(queryWrapper);
        return eduSubject;
    }
//这个函数是读取文件完了之后 在进行的操作
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
